package upload

import (
	"backend/pkg/file"
	"backend/pkg/logging"
	"backend/pkg/setting"
	"fmt"
	"github.com/satori/go.uuid"
	"io"
	"mime/multipart"
	"os"
	"path"
)

func GetFileFullUrl(name string) string {
	return setting.AppSetting.ImagePrefixUrl + "/" + name
}

func SaveFile(name string) (string, error) {
	src, err := os.Open(name)
	if err != nil {
		return "", err
	}
	uniqueName := GetUniqueName(name)
	if file.CheckNotExist(uniqueName) {
		tarFile := path.Join(GetImagePath(), uniqueName)
		tar, err := os.Create(tarFile)
		if err != nil {
			return "", err
		}
		_, err = io.Copy(tar, src)
		if err != nil {
			return "", err
		}
		err = tar.Close()
		if err != nil {
			return "", err
		}
	}
	err = src.Close()
	if err != nil {
		return "", err
	}
	return uniqueName, nil
}

func GetTempPath() string {
	filepath := setting.AppSetting.TempFilePath
	err := file.IsNotExistMkDir(filepath)
	if err != nil {
		logging.Warn(err)
	}
	return filepath
}

func GetUniqueName(filename string) string {
	ext := path.Ext(filename)
	uniqueName := uuid.NewV5(uuid.UUID{}, filename)
	return uniqueName.String() + ext
}

func GetImagePath() string {
	filepath := setting.AppSetting.ImageSavePath
	err := file.IsNotExistMkDir(filepath)
	if err != nil {
		logging.Warn(err)
	}
	return filepath
}

func CheckImageSize(f multipart.File) bool {
	size, err := file.GetSize(f)
	if err != nil {
		logging.Warn(err)
		return false
	}

	return size <= setting.AppSetting.ImageMaxSize
}

func CheckImage(src string) error {
	dir, err := os.Getwd()
	if err != nil {
		return fmt.Errorf("os.Getwd err: %v", err)
	}

	err = file.IsNotExistMkDir(dir + "/" + src)
	if err != nil {
		return fmt.Errorf("file.IsNotExistMkDir err: %v", err)
	}

	perm := file.CheckPermission(src)
	if perm == true {
		return fmt.Errorf("file.CheckPermission Permission denied src: %s", src)
	}

	return nil
}
